package handlers

import (
	"github.com/gin-gonic/gin"
	"logi-perm-sys/cache"
	"logi-perm-sys/modles"
	"logi-perm-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名和密码不能为空",
		})
		return
	}

	var user modles.User
	err := modles.DB.Where("username = ?", username).Debug().Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户登录密码错误超过3次禁止登录",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)

			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "用户登录密码错误超过3次2小时登录限制",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "记录错误日志",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	var userRoleAdd = modles.UserRole{
		Uid: uid,
		Rid: rid,
	}

	modles.DB.Debug().Create(&userRoleAdd)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}

func RolePermAdd(c *gin.Context) {

	rid, _ := strconv.Atoi(c.PostForm("rid"))
	pid, _ := strconv.Atoi(c.PostForm("pid"))

	var data = modles.RolePerm{
		Rid: rid,
		Pid: pid,
	}
	modles.DB.Debug().Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return

}

func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))

	/*
		SELECT * FROM
		roles
		LEFT JOIN user_roles on roles.id=user_roles.rid
		WHERE user_roles.uid=1

	*/

	var userRoleList []modles.Role

	modles.DB.Table("roles").
		Joins("LEFT JOIN user_roles on roles.id=user_roles.rid").
		Where(" user_roles.uid=?", uid).
		Debug().
		Find(&userRoleList)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": userRoleList,
	})
	return
}

func RolePermList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))

	/*
		SELECT * FROM
		perms
		LEFT JOIN role_perms on perms.id=role_perms.pid
		WHERE role_perms.rid=2

	*/

	var userRoleList []modles.Perm

	modles.DB.Table("perms").
		Joins("LEFT JOIN role_perms on perms.id=role_perms.pid").
		Where("role_perms.rid=?", rid).
		Debug().
		Find(&userRoleList)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": userRoleList,
	})
	return
}
